<template>
  <div class="tabs-container">
    <ExportAddTemplate v-if="types === 'add' || types === 'edit'"
                       ref="template"
                       :types="types"
                       :template-name="currentTabData.templateName"
                       :default-values="cloneExportData"
                       :current-tab-index="currentTabIndex"
                       :values="exportData[currentTabIndex].sheets"
                       @checked="checked" />
    <div v-else>
      <div class="tabs">
        <div v-for="(tab, index) in exportData"
             :key="index"
             :class="{ 'tab': true, 'deletable': index !== 0 , 'isActive': currentTabIndex === index}"
             @click="switchTab(tab, index)">
          <p class="tab-content">{{ tab.templateName }}</p>
          <span v-if="index !== 0"
                class="close-icon"
                @click="closeTab(tab.metaId, index)">
            <i class="el-icon-close"></i>
          </span>
        </div>
        <el-button v-if="exportData.length <= 5"
                   type="text"
                   class="add-button"
                   size="small"
                   icon="el-icon-plus"
                   @click="addTab()">新增模板</el-button>
      </div>
      <div v-if="exportData && exportData[currentTabIndex]"
           class="tab-column">
        <div v-if="currentTabIndex !== 0 "
             class="column_edit"><el-button type="text"
                     icon="el-icon-edit"
                     @click="handleEdit()">编辑模板</el-button></div>
        <span v-if="currentTabIndex === 0"
              class="column_title"><i class="el-icon-warning-outline" />系统推荐导出字段，不能取消勾选和拖动调整顺序</span>
        <div v-for="(item, index) in exportData[currentTabIndex].sheets"
             :key="index"
             class="column_sheets">
          <span class="column_item">{{ item.name }}</span>
          <ExportFieldColumn :values="item.columns"
                             :current-tab-index="currentTabIndex"
                             :types="types" />
        </div>
        <!-- {{ tabs[currentTabIndex].content }} -->
      </div>
    </div>
  </div>
</template>

<script>
import ExportAddTemplate from './ExportAddTemplate.vue'
import ExportFieldColumn from './ExportFieldColumn.vue'
// import _ from "lodash";
import { mapState } from "vuex";
import { customExports } from '@/api'

function processColumns (data, operation) {
  if (!data) {
    return;
  }

  data.flatMap(res => res.sheets)
    .flatMap(sheet => sheet.columns)
    .forEach(col => {
      if (col) {
        operation(col);
      }
    });
}

function checkedAlls (matchingData, operation) {
  if (!matchingData) {
    return;
  }
  matchingData.flatMap(sheet => sheet.columns)
    .forEach(col => {
      if (!col.locked) {
        operation(col);
      }
    });
}

export default {
  name: 'ExportTabs',
  components: { ExportAddTemplate, ExportFieldColumn },
  props: {
    types: {
      type: String,
      default: 'basis'
    }
  },
  data () {
    return {
      exportData: [],
      cloneExportData: [],
      currentTabIndex: 0,
      currentTabData: {}
    }
  },
  computed: {
    ...mapState({
      menus: (state) => state.menu.menu
    }),
    resourceId () {
      return this.menus?.resources.find(res => res.type === 4)?.resourceId;
    },
    processColumn () {
      return (data, operation) => processColumns(data, operation);
    },
    checkedAll () {
      return (matchingData, operation) => checkedAlls(matchingData, operation);
    }
  },
  created () {
    this.getExportTemplate()
  },
  methods: {
    switchTab (tab, index) {
      this.currentTabIndex = index;
      this.currentTabData = tab
      this.processColumn(this.exportData, col => col.fixed = true);
      this.$emit('input', 'basis', this.currentTabData)
    },
    addTab () {
      // if (this.exportData.length >= 5) {
      //   return this.$message.warning('最多新增5个模板')
      // }
      this.getExportTemplate()
      this.processColumn(this.exportData, col => delete col.fixed);
      this.$emit('input', 'add', this.currentTabData)
    },
    editTab () {
      this.processColumn(this.exportData, col => delete col.fixed);
      this.currentTabIndex = 0
      this.$emit('input', 'edit', this.currentTabData)
    },
    closeTab (metaId, index) {
      this.clearConfirm(metaId, index)
    },
    async getExportTemplate () {
      let response = await customExports.getExportMeta(this.resourceId)
      if (response.code === 0) {
        this.processColumn(response.data, col => col.fixed = true);
        this.exportData = response.data
        if (this.types === 'add') {
          const matchingData = response.data?.find(res => !res.metaId)?.sheets;
          this.cloneExportData = matchingData
        }
      }
    },
    async clearExportTemplate (metaId, index) {
      let response = await customExports.deleteExportMeta(metaId)
      if (response.code === 0) {
        this.$message.success(response.message)
        this.currentTabIndex = index - 1
        this.getExportTemplate()
      }
    },
    clearConfirm (metaId, index) {
      this.$confirm('此操作将永久删除该模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.clearExportTemplate(metaId, index)
      })
    },
    checked (value) {
      const index = this.types === 'add' ? 0 : this.currentTabIndex;
      const targetValue = value ? true : false; // 将value映射为true或false
      this.checkedAll(this.exportData[index]?.sheets, col => col.checked = targetValue);
    },
    handleEdit () {
      this.$emit('input', 'edit', this.currentTabData)
    }
  }
}
</script>

<style lang="scss" scoped>
.tabs {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
}

.tab {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 90px;
  height: 22px; /* 标签页的高度 */
  // background-color: #f0f0f0;
  border: 1px solid #e4e4e4;
  margin-bottom: 10px;
  padding: 5px;
  margin-right: 10px;
  border-radius: 3px;
  text-align: center;
  cursor: pointer;
  color: #666666;
  position: relative;
}

.tab-content {
  flex-grow: 1;
  cursor: pointer;
}
.tab-column {
  padding-top: 20px;
  .column_title {
    display: block;
    padding-bottom: 10px;
  }
  .column_sheets {
    padding-bottom: 20px;
  }
  .column_item {
    display: block;
    padding-bottom: 10px;
  }
  .el-icon-warning-outline {
    color: #eb662b;
    padding-right: 2px;
  }
  .column_edit {
    text-align: right;
  }
}

.close-icon {
  width: 17px;
  height: 17px;
  line-height: 17px;
  border-radius: 50%;
  background-color: #b3b3b3;
  position: absolute;
  right: -5px;
  top: -5px;
  color: #fff;
  cursor: pointer;
}
.add-button {
  height: 35px;
}
.isActive {
  background-color: #eb662b;
  border: 1px solid #eb662b;
  color: #fff;
}
</style>